<template>
    <div>
      <div class="login">
        <div class="cover">
          <h1 class="title">Free Chat 登录</h1>
          <div class="input">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
              <el-form-item prop="avatar">
                <div style="display: flex;justify-content: space-around">
                  <img v-if="ruleForm.avatar.length !== 0" :src="ruleForm.avatar" style="width: 80px;height: 80px;border-radius: 10px;">
                  <div v-else class="el-icon-user-solid" style="width: 80px;height: 80px;border-radius: 10px;
                    background-color: #909399;color: white;font-size: 50px;text-align: center;line-height: 80px"></div>
                </div>
              </el-form-item>
              <el-form-item prop="username">
                <el-input class="input-item" placeholder="用户名或邮箱" @blur="getAvatar" v-model="ruleForm.username">
                  <template slot="prepend"><i class="el-icon-user" style="font-size: 25px"></i></template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input class="input-item" placeholder="密码" show-password v-model="ruleForm.password">
                  <template slot="prepend"><i class="el-icon-lock" style="font-size: 25px"></i></template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button class="input-item" type="primary" v-if="processing" disabled="">登录中...</el-button>
                <el-button class="input-item" type="primary" v-else @click="slideVerify('ruleForm')">登 录</el-button>
              </el-form-item>
              <el-form-item>
                <div class="input-item" style="display: flex;justify-content: space-between">
                  <router-link to="/find">
                    <el-button type="info" plain size="mini">忘记密码</el-button>
                  </router-link>
                  <router-link to="/register">
                    <el-button type="primary" plain size="mini">注册</el-button>
                  </router-link>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <el-dialog title="登录验证" :visible.sync="slideVerifyVisible" width="350px">
        <vue-slide-verify v-if="slideVerifyVisible"
            :bg-src="bgSrc"
            :block-src="blockSrc"
            :success-text="successText"
            :fail-text="failText"
            @success="onSuccess"
            @fail="onFail"
            :text="text"
        ></vue-slide-verify>
      </el-dialog>
    </div>
</template>

<script>
import VueSlideVerify from 'vue-slide-verify'
export default {
  name: 'Login',
  data () {
    return {
      // 表单
      ruleForm: {
        username: '',
        password: '',
        avatar: ''
      },
      // 表单验证规则
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ]
      },
      processing: false,
      bgSrc: '@/assets/verify.jpg',
      blockSrc: 'path/to/block-image.png',
      successText: '验证成功',
      failText: '验证失败',
      text: '向右滑动',
      slideVerifyVisible: false
    }
  },
  components: {
    VueSlideVerify
  },
  mounted () {
    // this.$store.commit('setConversations', [])
    // this.$store.commit('setSelectedConversation', null)
    // this.$store.commit('setFriendRequestMsgArr', [])
  },
  methods: {
    getAvatar () {
      if (this.ruleForm.username.length !== 0) {
        let params = new URLSearchParams()
        params.append('username', this.ruleForm.username)
        this.axios.get(`/api/v1/user/avatar?username=${this.ruleForm.username}`).then((response) => {
          if (response.data.code === 1) {
            if (response.data.data === undefined) {
              this.ruleForm.avatar = ''
            } else {
              this.ruleForm.avatar = response.data.data
            }
          } else {
            this.ruleForm.avatar = ''
          }
        })
      }
    },
    onSuccess () {
      this.slideVerifyVisible = false
      this.login()
    },
    onFail () {
      console.log('验证失败')
    },
    slideVerify (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.slideVerifyVisible = true
        }
      })
    },
    login () {
      this.processing = true
      let username = this.ruleForm.username
      let password = this.ruleForm.password
      let params = new URLSearchParams()
      params.append('username', username)
      params.append('password', password)
      this.axios.post('/api/v1/user/login', params).then((response) => {
        if (response.data.code === 1) {
          let user = response.data.data
          // 保存当前登录用户数据
          this.$store.commit('setCurrentUser', user)
          console.log('currentUser = ' + JSON.stringify(user))
          // 保存token
          localStorage.setItem('token', user.token)
          // 初始化用户信息
          this.$store.commit('setCurrentUserInfo', user.id)
          this.$store.commit('setSelectedConversation', null)
          // 置socket为null
          this.$store.commit('setSocket', null)

          this.$router.push('/home')
        } else {
          this.processing = false
          this.$message({
            message: response.data.message,
            type: 'error'
          })
        }
      }).catch((error) => {
        this.processing = false
        this.$message({
          message: error,
          type: 'error'
        })
        console.error(error)
      })
    }
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus">
.el-form-item
  margin-bottom 0
.cover
  position absolute
  top 0
  bottom 0
  left 0
  width 100%
  background-color rgba(0, 0, 0, 0.51)
  z-index 2
.login
  position absolute
  top 0
  bottom 0
  left 0
  width 100%
  background-image url("../assets/background.jpg")
  background-size cover
  background-repeat no-repeat
  .title
    padding-top 100px
    padding-bottom 30px
    text-align center
    font-size 35px
    font-weight bold
    color #ffffff
  .input
    min-width 200px
    max-width 400px
    margin 20px auto
    padding 20px
    border-radius 20px
    background white
    .input-item
      width 100%
      margin-top 30px
</style>
